package br.com.onlinebidding.mb;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import br.com.onlinebidding.facade.BidFacade;
import br.com.onlinebidding.model.Bid;
import br.com.onlinebidding.model.User;

@SessionScoped
@ManagedBean(name = "bidMB")
public class BidMB extends AbstractMB implements Serializable {

	public static final String INJECTION_NAME = "#{bidMB}";
	private static final long serialVersionUID = 1L;

	private Bid bid;
	private List<Bid> bids;
	private BidFacade bidFacade;
	
	public BidMB(){
		this.bid = new Bid();
	}
		
	public BidFacade getBidTFacade() {
		if (this.bidFacade == null) {
			this.bidFacade = new BidFacade();
		}
		return this.bidFacade;
	}

	public User getUserLogado(){
		
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		User userlogado = (User)request.getSession().getAttribute("userlogado");
		
		return userlogado;
	}
	
	public  Date getDateTimeOffer(){
		
		Date d = new Date();  
		
	    return d;
	}
	
	public void insertBid() {
		
		this.bid.setIdUser(getUserLogado());
		this.bid.setDateTimeOffer(getDateTimeOffer());
		
		try {
			getBidTFacade().insertBid(this.bid);
			closeDialog();
			displayInfoMessageTo("Inserido Com Sucesso!");
			loadBids();
			resetBid();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao inserir . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}
	
	public void deleteBid() {
		try {
			getBidTFacade().deleteBid(this.bid);
			closeDialog();
			displayInfoMessageTo("Excluido Com Sucesso!");
			loadBids();
			resetBid();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao excluir  . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}

	public List<Bid> getAllBids() {
		if (this.bids == null) {
			loadBids();
		}

		return this.bids;
	}

	private void loadBids() {
		this.bids = getBidTFacade().listAll();
	}

	public void resetBid() {
		this.bid = new Bid();
	}


	public Bid getBid() {
		return bid;
	}

	public void setBid(Bid bid) {
		this.bid = bid;
	}

	public List<Bid> getBids() {
		return bids;
	}

	public void setBids(List<Bid> bids) {
		this.bids = bids;
	}

	public BidFacade getBidFacade() {
		return bidFacade;
	}

	public void setBidFacade(BidFacade bidFacade) {
		this.bidFacade = bidFacade;
	}
}
